import { CodecType, Uint16, Uint8, makeSimpleReq } from "./codec";
import { serialPort } from "./conn";
import { Cmd, Type, createRespPromise } from "./proto";

let globaleSeq = 0;

function getSeq() {
    let seq = globaleSeq;
    globaleSeq += 1;
    if (globaleSeq > 255) {
        globaleSeq = 0;
    }
    return seq;
}

async function write(cmd: number, ...args: CodecType[]) {
    const seq = getSeq();
    const promise = createRespPromise(Type.SIMPLE_RES, seq, 1000, "返回超时");
    const buf = makeSimpleReq(seq, cmd, ...args);
    await serialPort.write(buf);
    const result = await promise;
    const ec = result[3];
    console.log(result);
    if (ec != 0) {
        throw `错误:${ec}`
    }
}

export const service = {

    async motorCtrl(id: number, dir: number) {
        await write(Cmd.MOTOR_CTRL, new Uint8(id), new Uint8(dir));
    },

    async numLedCtrl(id: number, value: number) {
        await write(Cmd.NUM_LED_CTRL, new Uint8(id), new Uint16(value));
    },

    async debugIoCtrl(port: number, pin: number, level: number) {
        await write(Cmd.DEBUG_IO, new Uint8(port), new Uint8(pin), new Uint8(level));
    }
}
